package com.atguigu.gmall.common.config.exception.handle;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//@ControllerAdvice//controller 的异常切面；aop advice 通知
//@ResponseBody//返回的是json
@RestControllerAdvice//复合注解
@Slf4j
public class GlobalExceptionHandle {

    //处理所有controller出现的异常
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.info("系统异常：",e);
        Result<Object> fail = Result.fail();
        fail.setMessage(e.getMessage());
        return fail;
    }

    //处理异常：提交订单的参数校验
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        //从异常中拿到校验结果
        BindingResult bindingResult = exception.getBindingResult();
        Map<Object, Object> map = new HashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String field = error.getField();//错误的属性
            String message = error.getDefaultMessage();//错误的消息
            map.put(field, message);
        }
        Result<Map<Object, Object>> build = Result.build(map, ResultCodeEnum.INVAILD_PARAM);
        return build;
    }

    //和业务有关的异常，用GmallException
    @ExceptionHandler(GmallException.class)
    public Result gmallException(GmallException e){
        Result<Object> fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        return fail;
    }
}
